package com.sanjishu.enterlab.electricity.sale.service;

import com.sanjishu.enterlab.electricity.sale.controller.Response;
import com.sanjishu.enterlab.electricity.sale.domain.*;
import com.sanjishu.enterlab.electricity.sale.mapper.*;
import com.sanjishu.enterlab.electricity.sale.utils.Page;
import com.sanjishu.enterlab.electricity.sale.utils.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class CompanyInfoService {

    @Autowired
    private CompanyInfoMapper companyInfoMapper;
    @Autowired
    private DetailInfoMapper detailInfoMapper;
    @Autowired
    private CityMapper cityMapper;
    @Autowired
    private CompanyBakMapper companyBakMapper;
    @Autowired
    private ContractInfoMapper contractInfoMapper;
    @Autowired
    private SmsService smsService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMessageService userMessageService;
    @Value("${page.size}")
    private Integer pageSize;

    public List<CompanyInfo> findByUserId(Integer userId) {
        return companyInfoMapper.findByUserId(userId);
    }

    public DetailInfo findByCompanyId(Integer companyInfoId) {
        return detailInfoMapper.findByCompanyId(companyInfoId);
    }

    public CompanyInfo findById(Integer companyId) {
        return companyInfoMapper.selectByPrimaryKey(companyId);
    }

    public CompanyInfo findByCompanyBakId(Integer companyBakId){
        return companyInfoMapper.findByCompanyBakId(companyBakId);
    }

    public DetailInfo findByDetailId(Integer id) {
        return detailInfoMapper.selectByPrimaryKey(id);
    }

    public List<CompanyInfo> findOtherCompany(Integer userId, Integer companyId) {
        return companyInfoMapper.findOtherCompany(userId, companyId);
    }

    public CompanyInfo createCompany(String companyName, String creditCode, String operName, String address, String elecFor,
                              String contractName, String contractPhone, String wxNum, String capital,
                              String establishDate, String types, String validPeriod, String imgUrl, Integer userId,
                              Integer cityId, Integer adminId, Date relatedAt, Integer companyBakId) {
        CompanyInfo companyInfo = new CompanyInfo();
        companyInfo.setName(companyName);
        companyInfo.setAddress(address);
        companyInfo.setCreditCode(creditCode);
        companyInfo.setOperName(operName);
        companyInfo.setElecFor(elecFor);
        companyInfo.setUserId(userId);
        companyInfo.setContractName(contractName);
        companyInfo.setContractPhone(contractPhone);
        companyInfo.setStatus(CompanyInfo.STATUS_NORMAL);
        companyInfo.setLicenseImgUrl(imgUrl);
        companyInfo.setWxNum(wxNum);
        companyInfo.setEstablishDate(establishDate);
        companyInfo.setTypes(types);
        companyInfo.setValidPeriod(validPeriod);
        companyInfo.setCapital(capital);
        companyInfo.setCreatedAt(new Date());
        companyInfo.setUpdatedAt(new Date());
        if (cityId != null) {
            companyInfo.setCityId(cityId);
        } else {
            City city = getCityByCreditCode(creditCode);
            if (city != null) {
                companyInfo.setCityId(city.getId());
            }
        }
        if (adminId != null) {
            companyInfo.setAdminId(adminId);
        }
        if (relatedAt != null) {
            companyInfo.setRelatedAt(relatedAt);
        }
        CompanyBak companyBak = null;
        if (companyBakId != null) {
            companyBak = companyBakMapper.selectByPrimaryKey(companyBakId);
            if (companyBak == null) {
                companyBak = companyBakMapper.findByName(companyName);
            }
        }
        if (companyBak != null) {
            companyInfo.setCompanyBakId(companyBak.getId());
            companyInfo.setBelongOrg(companyBak.getBelongOrg());
        }
        companyInfoMapper.insert(companyInfo);
        return companyInfo;
    }

    public CompanyInfo updateCompany(Integer id, String companyName, String creditCode, String operName,
                              String address, String elecFor,
                              String contractName, String contractPhone, String wxNum, String capital,
                              String establishDate, String types, String validPeriod, String imgUrl,
                              Integer cityId, Integer adminId, Date relatedAt) {
        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(id);
        if (companyName != null && companyName != "") {
            companyInfo.setName(companyName);
        }
        if (address != null && address != "") {
            companyInfo.setAddress(address);
        }
        if (creditCode != null && creditCode != "") {
            companyInfo.setCreditCode(creditCode);
        }
        if (operName != null && operName != "") {
            companyInfo.setOperName(operName);
        }
        if (elecFor != null && elecFor != "") {
            companyInfo.setElecFor(elecFor);
        }
        if (contractName != null && contractName != "") {
            companyInfo.setContractName(contractName);
        }
        if (contractPhone != null && contractPhone != "") {
            companyInfo.setContractPhone(contractPhone);
        }
        if (imgUrl != null && imgUrl != "") {
            companyInfo.setLicenseImgUrl(imgUrl);
        }
        if (wxNum != null && wxNum != "") {
            companyInfo.setWxNum(wxNum);
        }
        if (establishDate != null && establishDate != "") {
            companyInfo.setEstablishDate(establishDate);
        }
        if (types != null && types != "") {
            companyInfo.setTypes(types);
        }
        if (validPeriod != null && validPeriod != "") {
            companyInfo.setValidPeriod(validPeriod);
        }
        if (capital != null && capital != "") {
            companyInfo.setCapital(capital);
        }
        companyInfo.setUpdatedAt(new Date());
        if (cityId != null) {
            companyInfo.setCityId(cityId);
        } else {
            if (companyInfo.getCityId() == null) {
                City city = getCityByCreditCode(creditCode);
                if (city != null) {
                    companyInfo.setCityId(city.getId());
                }
            }
        }
        if (companyInfo.getBelongOrg() == null) {
            CompanyBak companyBak = companyBakMapper.findByName(companyName);
            if (companyBak != null) {
                companyInfo.setCompanyBakId(companyBak.getId());
                companyInfo.setBelongOrg(companyBak.getBelongOrg());
            }
        }
        if (adminId != null) {
            companyInfo.setAdminId(adminId);
        }
        if (relatedAt != null) {
            companyInfo.setRelatedAt(relatedAt);
        }
        companyInfoMapper.updateByPrimaryKey(companyInfo);
        return companyInfo;
    }

    public City getCityByCreditCode(String creditCode) {
        if (creditCode != null && creditCode.length() >= 7) {
            return cityMapper.findByPreCode(creditCode.substring(2,7));
        } else {
            return cityMapper.findByPreCode(creditCode);
        }
    }

    public String getOldElec(String name) {
        String elecConsumption = null;
        CompanyBak companyBak = companyBakMapper.findByName(name);
        if (companyBak != null) {
            elecConsumption = companyBak.getElecConsumption();
        }
        return elecConsumption;
    }

    @Transactional
    public Response unValidate(String str, Integer companyId, Integer contractId) {
        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(companyId);
        ContractInfo contractInfo = contractInfoMapper.selectByPrimaryKey(contractId);
        User user = userMapper.selectByPrimaryKey(contractInfo.getUserId());
        if (companyInfo != null) {
            companyInfo.setStatus(CompanyInfo.STATUS_UNVERIFIED);
            companyInfo.setUpdatedAt(new Date());
            companyInfoMapper.updateByPrimaryKey(companyInfo);
            contractInfo.setStatus(ContractInfo.STATUS_UNVERIFIED);
            contractInfo.setUpdateAt(new Date());
            contractInfoMapper.updateByPrimaryKey(contractInfo);
            if (user != null) {
                Map<String, String> map = new HashMap<>();
                map.put("name", companyInfo.getName());
                map.put("str", str);
                smsService.sendMessage(user.getPhone(), "SMS_158050311", map);
                userMessageService.createUserMessage(user.getId(), companyId, Message.TYPE_UNVALIDATED,
                        "您提交的"+companyInfo.getName()+":"+str+"信息填写有问题，审核未通过，请尽快重新修改。");
            }
        }
        return Response.buildSuccess("审核未通过，审核短信已经发送用户");
    }

    public Response validate(Integer companyId, Integer contractId) {
        CompanyInfo companyInfo = companyInfoMapper.selectByPrimaryKey(companyId);
        ContractInfo contractInfo = contractInfoMapper.selectByPrimaryKey(contractId);
        User user = userMapper.selectByPrimaryKey(contractInfo.getUserId());
        if (companyInfo != null) {
            companyInfo.setStatus(CompanyInfo.STATUS_VERIFIED);
            companyInfo.setUpdatedAt(new Date());
            companyInfoMapper.updateByPrimaryKey(companyInfo);
            contractInfo.setStatus(ContractInfo.STATUS_VERIFIED);
            contractInfo.setUpdateAt(new Date());
            contractInfoMapper.updateByPrimaryKey(contractInfo);
            if (user != null) {
                Map<String, String> map = new HashMap<>();
                map.put("company", companyInfo.getName());
                smsService.sendMessage(user.getPhone(), "SMS_158050316", map);
            }
        }
        return Response.buildSuccess("审核通过，审核短信已经发送用户");
    }

    public Page<CompanyInfo> findByAdminId(Integer userId, Integer page, Integer currentSize) {
        Long count = companyInfoMapper.countByAdminId(userId, null);
        if (currentSize == 0) {
            currentSize = pageSize;
        }
        if (count == 0) {
            return new Page<CompanyInfo>(new PageRequest(1, currentSize), new ArrayList<>(), count);
        }
        PageRequest request = new PageRequest(page, currentSize);
        List<CompanyInfo> result = companyInfoMapper.findByAdminId(userId, null, request);
        Page<CompanyInfo> pageData = new Page<CompanyInfo>(request, result, count);
        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), currentSize);
            result = companyInfoMapper.findByAdminId(userId, null, request);
            pageData = new Page<>(request, result, count);
        }
        return pageData;
    }

    public Page<CompanyInfo> findMyContracts(Integer userId, Integer page, Integer currentSize) {
        Long count = companyInfoMapper.countByAdminId(userId, 1);
        if (currentSize == 0) {
            currentSize = pageSize;
        }
        if (count == 0) {
            return new Page<CompanyInfo>(new PageRequest(1, currentSize), new ArrayList<>(), count);
        }
        PageRequest request = new PageRequest(page, currentSize);
        List<CompanyInfo> result = companyInfoMapper.findByAdminId(userId, 1, request);
        Page<CompanyInfo> pageData = new Page<CompanyInfo>(request, result, count);
        if (pageData.getCurrentPage() > pageData.getTotalPage()) {
            request = new PageRequest(pageData.getTotalPage(), currentSize);
            result = companyInfoMapper.findByAdminId(userId, 1, request);
            pageData = new Page<>(request, result, count);
        }
        return pageData;
    }



    public CompanyInfo getByName(String name) {
        return companyInfoMapper.findByName(name);
    }




}
